#!/usr/bin/env python3

import shelve
import sys
import os
import re
from github_social_network_graph import GH_User

CSV_DELIM = ";"
CSV_ESCAPE = "\\"
FIELDS = ['login',
          'name',
          'email',
          'location',
          'id',
          'type',
          'created_at',
          'sequence_number',
          'followers_number',
          'following_number']

def continue_yesno():
    while 1:
        ans = input('continue? [yn] ')
        if ans == 'y' or ans == '':
            return 1
        elif ans == 'n':
            return 0
        else:
            print('response "{0}" not understood'.format(ans))

def escape_meta_symbols(string, metasyms, esc):
    i = 0
    ret = ''
    while i < len(string):
        if string[i] in metasyms:
            ret += esc
        ret += string[i]
        i += 1
    return ret

def escape_csv_tuple(arg):
    if type(arg) != type(list()):
        try:
            arg = list(arg)
        except:
            print("bad argument")
            return 1
    ret = []
    for s in arg:
        s = escape_meta_symbols(s, [CSV_DELIM, CSV_ESCAPE], CSV_ESCAPE)
        ret.append(s)
    ret = CSV_DELIM.join(ret)
    return ret

def main():
    if not os.access(sys.argv[1], os.R_OK):
        print('usage: {0} [graph_filename]'.format(sys.argv[0]))
        return 1
    g = shelve.open(sys.argv[1], 'r')
    pool = g['pool']
    g.close()
    del g
    roster = [x for x in pool.keys()]
    roster.sort()

    if os.access(sys.argv[1] + '-nodes.csv', os.F_OK):
        print('file already exists: {0}'.format(sys.argv[1] + '-nodes.csv'))
        if not continue_yesno():
            return 0
    if os.access(sys.argv[1] + '-edges.csv', os.F_OK):
        print('file already exists: {0}'.format(sys.argv[1] + '-edges.csv'))
        if not continue_yesno():
            return 0

    f_nodes = open(sys.argv[1] + '-nodes.csv', 'w')
    f_nodes.write(escape_csv_tuple(FIELDS) + '\n')
    for guy in roster:
        info = []
        for field in FIELDS:
            info.append(str(getattr(pool[guy], field, '')))
        f_nodes.write(escape_csv_tuple(info) + '\n')
    f_nodes.flush()
    f_nodes.close()
    del f_nodes

    f_edges = open(sys.argv[1] + '-edges.csv', 'w')
    f_edges.write(escape_csv_tuple(['src', 'dst']) + '\n')
    for bloke in roster:
        for chap in pool[bloke].following:
            if chap in roster:
                f_edges.write(escape_csv_tuple([bloke, chap]) + '\n')
    f_edges.flush()
    f_edges.close()
    del f_edges

if __name__ == '__main__':
    main()
